<?php

include("lib/db.php");

header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');


$xml = new SimpleXMLElement('<xml/>');

if (isset($_GET['action']) && $_GET['action'] == 'login') {
    $track = $xml->addChild('item');

	$username = $_GET['username'];
	$password = $_GET['password'];

	$query = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'";

        $result = mysql_query($query) or die(mysql_error());
	$row = mysql_fetch_array($result);

    if ($row) {
        $track->addChild('status', "ok");
    } else {
        $track->addChild('status', "no");
    }
} else if (isset($_GET['action']) && $_GET['action'] == 'getMessage') {

	$username = $_GET['username'];
	$password = $_GET['password'];

	$query = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'";

        $result = mysql_query($query) or die(mysql_error());
	$rowUser = mysql_fetch_array($result);

    if (!$rowUser)
	die();

	if(isset($_GET['news']) && $_GET['news'] == "true")
	$status =  "AND status = '1'";
	else
	$status = "AND status = '0'";

    //Get records from database
    $result = mysql_query("SELECT * FROM message WHERE id IN (SELECT messageId FROM userMessage WHERE userId = ".$rowUser['id']." ".$status.")  order by id DESC");


    while ($row = mysql_fetch_array($result)) {
        $track = $xml->addChild('item');
        $track->addChild('id', $row['id']);
        $track->addChild('title', $row['title']);
        $track->addChild('content', $row['content']);
    }

    //delete
    $result = mysql_query("update userMessage set status = '0' WHERE userId = '".$rowUser['id']."'");
} else if (isset($_GET['action']) && $_GET['action'] == 'delete') {

	$username = $_GET['username'];
	$password = $_GET['password'];

	$query = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'";

        $result = mysql_query($query) or die(mysql_error());
	$rowUser = mysql_fetch_array($result);

	$result = mysql_query("delete from userMessage WHERE userId = '".$rowUser['id']."' and messageId= '".$_GET['messageId']."'");

} else {
    $track = $xml->addChild('item');
    $track->addChild('status', "no");
}
print($xml->asXML());

?>
